package com.mifengs.mall.widget;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.DownloadListener;
import android.webkit.GeolocationPermissions;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.mifengs.commonbase.util.DeviceInfoUtil;
import com.mifengs.commonbase.util.PreferenceUtils;
import com.mifengs.mall.Constant;
import com.mifengs.mall.MallApplication;
import com.mifengs.mall.R;
import com.mifengs.mall.ui.main.MainActivity;
import com.mifengs.mall.ui.web.CommonWebActivity;
import com.mifengs.mall.util.FileManager;
import com.mifengs.mall.util.WebUtils;

import java.io.File;
import java.util.Map;

/**
 * Created by Administrator on 2017/10/23.
 */

public class MyWebView extends BridgeWebView {


    private Context mContext;

    private OnProgressChangerListener mProgressListener;

    private boolean isTouchEnable = true;

    public MyWebView(Context context) {
        super(context);
        init(context);
    }

    public MyWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MyWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public void setProgressListener(OnProgressChangerListener listener) {
        this.mProgressListener = listener;
    }

    public void setTouchEnable(boolean touchEnable) {
        isTouchEnable = touchEnable;
    }

    private void init(Context context) {
        this.mContext = context;
        WebSettings webSettings = getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setDatabaseEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        // App中打开web时的User-Agent
        String ua = webSettings.getUserAgentString();
        if(mContext instanceof MainActivity){
            ua = ua + " " + "mfsc_android" +" v_"+ DeviceInfoUtil.getAppVersion(mContext) + "_ismain" + android.os.Build.BRAND;
        }else{
            ua = ua + " " + "mfsc_android" +" v_"+ DeviceInfoUtil.getAppVersion(mContext) + android.os.Build.BRAND;
        }
        webSettings.setUserAgentString(ua);
        setDownloadListener(new MyWebViewDownLoadListener());
        setWebChromeClient(new MyWebChromeClient());
        //syncCookie();
    }
    /**
     * 图片选择回调
     */
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    public static final int SELECT_PIC_BY_TACK_PHOTO = 100;

    class MyWebChromeClient extends WebChromeClient {
        // 配置权限（同样在WebChromeClient中实现）
        @Override
        public void onGeolocationPermissionsShowPrompt(String origin,
                                                       GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
            super.onGeolocationPermissionsShowPrompt(origin, callback);
        }

        // For Android < 3.0
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            mUploadMessage = uploadMsg;
            showOptions();
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            mUploadMessage = uploadMsg;
            showOptions();
        }

        // For Android > 4.1.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg,
                                    String acceptType, String capture) {
            mUploadMessage = uploadMsg;
            showOptions();
        }

        // For Android > 5.0支持多张上传
        @Override
        public boolean onShowFileChooser(WebView webView,
                                         ValueCallback<Uri[]> uploadMsg,
                                         FileChooserParams fileChooserParams) {
            mUploadCallbackAboveL = uploadMsg;
            showOptions();
            return true;
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            onReceivedTitleListener.recevied(title);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if(mProgressListener!=null){
                mProgressListener.onProgressChanged(newProgress);
            }
        }


    }

    private Uri fileUri;
    public static final int TYPE_REQUEST_PERMISSION = 3;
    public static final int TYPE_CAMERA = 1;
    public static final int TYPE_GALLERY = 2;
    public static final int TYPE_LOGIN = 3;

    /**
     * 包含拍照和相册选择
     */
    public void showOptions() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
        alertDialog.setOnCancelListener(new ReOnCancelListener());
        alertDialog.setTitle("选择");
        alertDialog.setItems(R.array.options,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
//                            if (ContextCompat.checkSelfPermission(mContext,
//                                    Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
//                                // 申请WRITE_EXTERNAL_STORAGE权限
//                                ActivityCompat.requestPermissions((Activity) mContext,
//                                                new String[]{Manifest.permission.CAMERA},
//                                                TYPE_REQUEST_PERMISSION);
//                            } else {
//                                toCamera();
//                            }
                                if(mContext instanceof  CommonWebActivity){
                                ((CommonWebActivity)mContext).requestPermissionsCamera();
                            }
                        } else {
                            Intent i = new Intent(Intent.ACTION_PICK,
                                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI);// 调用android的图库
                            ((Activity) mContext).startActivityForResult(i, TYPE_GALLERY);
                        }
                    }
                });
        alertDialog.show();
    }

    private static Uri getOutputMediaFileUri() {
        return Uri.fromFile(FileManager.getImgFile(MallApplication.getInstance().getApplicationContext()));
    }

    private class ReOnCancelListener implements
            DialogInterface.OnCancelListener {

        @Override
        public void onCancel(DialogInterface dialogInterface) {
            if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
            }
            if (mUploadCallbackAboveL != null) {
                mUploadCallbackAboveL.onReceiveValue(null);
                mUploadCallbackAboveL = null;
            }
        }
    }

    // 请求拍照
    public void toCamera() {
//        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 调用android的相机
//        // 创建一个文件保存图片
       // fileUri = getOutputMediaFileUri();
//        Log.d("MainActivity", "fileUri=" + fileUri);
//        intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
//        ((Activity) mContext).startActivityForResult(intent, TYPE_CAMERA);


        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 调用android的相机
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            String authority = mContext.getPackageName() + ".provider";
            File newFile = new File(mContext.getCacheDir(), "default_image.jpg");
            fileUri = FileProvider.getUriForFile(mContext, authority,newFile);
//            fileUri = FileProvider.getUriForFile(mContext, authority, FileManager.getImgFile(MallApplication.getInstance().getApplicationContext()));
            mContext.grantUriPermission(mContext.getPackageName(),fileUri,Intent.FLAG_GRANT_READ_URI_PERMISSION);
//            //加入uri权限 要不三星手机不能拍照
//            List<ResolveInfo> resInfoList = mContext.getPackageManager().queryIntentActivities
//                    (intent, PackageManager.MATCH_DEFAULT_ONLY);
//            for (ResolveInfo resolveInfo : resInfoList) {
//                String packageName = resolveInfo.activityInfo.packageName;
//                mContext.grantUriPermission(packageName, fileUri, Intent
//                        .FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
//            }
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

        } else {
            fileUri = getOutputMediaFileUri();
            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
        }
        ((Activity) mContext).startActivityForResult(intent, TYPE_CAMERA);

    }

    /**
     * 回调到网页
     *
     * @param isCamera
     * @param uri
     */
    public void onActivityCallBack(boolean isCamera, Uri uri) {
        if (isCamera) {
            uri = fileUri;
        }
        if (mUploadCallbackAboveL != null) {
            Uri[] uris = new Uri[]{uri};
            mUploadCallbackAboveL.onReceiveValue(uris);
            mUploadCallbackAboveL = null;
        } else if (mUploadMessage != null) {
            mUploadMessage.onReceiveValue(uri);
            mUploadMessage = null;
        } else {
            //Toast.makeText(mContext, "无法获取数据", Toast.LENGTH_LONG).show();
        }
    }


    public void onActivityNoBack() {
        if (mUploadMessage != null) {
            mUploadMessage.onReceiveValue(null);
            mUploadMessage = null;
        }
        if (mUploadCallbackAboveL != null) {
            mUploadCallbackAboveL.onReceiveValue(null);
            mUploadCallbackAboveL = null;
        }
    }

    private class MyWebViewDownLoadListener implements DownloadListener {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                                    long contentLength) {
            Log.i("tag", "url="+url);
            Log.i("tag", "userAgent="+userAgent);
            Log.i("tag", "contentDisposition="+contentDisposition);
            Log.i("tag", "mimetype="+mimetype);
            Log.i("tag", "contentLength="+contentLength);
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            ((Activity)mContext).startActivity(intent);
        }
    }


    /**
     * 给WebView同步Cookie
     */
    public void syncCookie() {
        CookieSyncManager.createInstance(mContext);
        String domain = Constant.BaseUrl.split("//")[1];
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        boolean isLogin =  PreferenceUtils.getLoginStatus();
        cookieManager.removeSessionCookie();
        if(isLogin){
            String token = PreferenceUtils.getToken();
            String cookie = "LS_TOKEN=" + token;
            cookieManager.setCookie(domain,cookie);
        }
        CookieSyncManager.getInstance().sync();// To get instant sync instead of waiting for the timer to trigger, the host can call this.
    }

    public void cleanCookie(){
        CookieSyncManager.createInstance(mContext);
        String domain = Constant.BaseUrl.split("//")[1];
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
        CookieSyncManager.getInstance().sync();
    }


    public interface OnProgressChangerListener{
        void onProgressChanged(int progress);
    }

    private OnLoadFinishListener mOnLoadFinishListener;

    private onReceivedTitleListener onReceivedTitleListener;

    public interface OnLoadFinishListener{
        public void onLoadFinish();
    }

    public interface onReceivedTitleListener{
        void recevied(String title);
    }

    private boolean isFirst = false;


    public void setOnLoadFinishListener(OnLoadFinishListener onLoadFinishListener){
        this.mOnLoadFinishListener = onLoadFinishListener;
    }

    public void setOnReceivedTitleListener(MyWebView.onReceivedTitleListener onReceivedTitleListener) {
        this.onReceivedTitleListener = onReceivedTitleListener;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if(isTouchEnable){
            return super.onTouchEvent(event);
        }else{
            return false;
        }
    }


    @Override
    public void loadUrl(String url) {
        if((!TextUtils.isEmpty(url))&&url.startsWith("http")){
            setTiteGoneVisible(url);
            super.loadUrl(addOrRemoveParams(url));
        }else{
            super.loadUrl(url);
        }
    }


    public void setTiteGoneVisible(String url){
        if(getContext() instanceof CommonWebActivity){
            if(url.contains("wap/page")||url.contains("wap/seckill")){
                ((CommonWebActivity) getContext()).setTopBarGone();
            }else{
                Uri uri = Uri.parse(url);
                String isNeedTopBar =  uri.getQueryParameter("isNeedTopBar");
                if(!TextUtils.isEmpty(isNeedTopBar)&& isNeedTopBar.equals("1")){
                    ((CommonWebActivity) getContext()).setTopBarGone();
                }
            }
        }
    }

    @Override
    public void loadUrl(String url, Map<String, String> additionalHttpHeaders) {
        if((!TextUtils.isEmpty(url))&&url.startsWith("http")){
            setTiteGoneVisible(url);
            super.loadUrl(addOrRemoveParams(url), additionalHttpHeaders);
        }else{
            super.loadUrl(url, additionalHttpHeaders);
        }
    }


    public String addOrRemoveParams(String url){
        if(PreferenceUtils.getLoginStatus()){
            return WebUtils.addSignParam(url);
        }else{
            return WebUtils.removeSignParam(url);
        }
    }



}
